package com.idudiao.sc.common.core.util;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 当前web应用工具类
 * @author songyinyin
 */
@Slf4j
public class WebUtils extends org.springframework.web.util.WebUtils {

    private static RedisTemplate redisTemplate = SpringContextHolder.getBean("redisTemplate");

    /**
     * 从redis中获取值
     * @param key 键
     * @return 值
     */
    public static Object getRedisValue(String key) {
        return StrUtil.isBlank(key) ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 从redis中获取hash值
     * @param key 键
     * @return 值
     */
    public static Map getRedisHashValue(String key) {
        return StrUtil.isBlank(key) ? null : transfer(redisTemplate.opsForHash().entries(key));
    }

    /**
     * 去掉双引号
     * @param map
     * @return
     */
    private static Map transfer(Map map) {
        Map result = new HashMap();
        map.forEach((k, v) -> {
            if (k.toString().startsWith("\"") && k.toString().endsWith("\"")) {
                k = k.toString().substring(1, k.toString().length()-1);
            }
            if (v.toString().startsWith("\"") && v.toString().endsWith("\"")) {
                v = v.toString().substring(1, v.toString().length()-1);
            }
            result.put(k, v);
        });
        return result;
    }

    /**
     * 从redis中存值
     * @param key 键
     * @param value 值
     */
    public static void setRedisHashValue(String key, Map value) {
        redisTemplate.opsForHash().putAll(key, value);
    }


    /**
     * 读取cookie
     *
     * @param name cookie name
     * @return cookie value
     */
    public static String getCookieVal(String name) {
        HttpServletRequest request = WebUtils.getRequest();
        Assert.notNull(request, "request from RequestContextHolder is null");

        Cookie cookie = getCookie(request, name);
        return cookie != null ? cookie.getValue() : null;
    }

    /**
     * 获取 HttpServletRequest
     *
     * @return {HttpServletRequest}
     */
    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 获取 HttpServletResponse
     *
     * @return {HttpServletResponse}
     */
    public static HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }
}
